package com.devmarvel.creditcardentry.fields;

import com.devmarvel.creditcardentry.ResourceTable;
import ohos.agp.components.AttrSet;
import ohos.agp.render.Paint;
import ohos.agp.utils.Rect;
import ohos.agp.utils.TextAlignment;
import ohos.app.Context;

public class ZipCodeText extends CreditEntryFieldBase {

    private int maxChars;

    private String mHelperText;

    public ZipCodeText(Context context) {
        super(context);
        init();
    }

    public ZipCodeText(Context context, AttrSet attrs) {
        super(context, attrs);
        init();
    }

    public ZipCodeText(Context context, AttrSet attrs, String defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    void init() {
        super.init();
        maxChars = 5;
        setMaxChars(maxChars);
        setHint("ZIP      ");
        Paint textPaint = new Paint();
        textPaint.setTextSize(getTextSize());
        Rect bounds = textPaint.getTextBounds("MMMMMM");
        setMinWidth(bounds.getWidth() + (2 * HORIZONTAL_PADDING) + PADDING_OFFSET);
        setMinHeight(bounds.getHeight());
        setTextAlignment(TextAlignment.LEFT);
    }

    @Override
    public void setHelperText(String helperText) {
        mHelperText = helperText;
    }

    @Override
    public String getHelperText() {
        return (mHelperText != null ? mHelperText : context.getString(ResourceTable.String_ZipHelp));
    }

    @Override
    public void textChanged(CharSequence s, int start, int before, int end) {
        validate(s);
    }

    @Override
    public void afterTextChanged(String text) {
        String formatted = text;
        if (text.length() > maxChars) {
            formatted = text.substring(0, maxChars);
        }
        formatAndSetText(formatted);
        validate(formatted);
    }

    private void validate(CharSequence s) {
        // Check if only digits (for US zip codes)
        if (s.toString().matches("^\\d+$")) {
            if (s.length() == maxChars) {
                setValid(true);
                delegate.onZipCodeValid();
            } else {
                setValid(false);
            }

            // For other countries like the UK, postal codes are alphanumeric
            // and can be anything from 3 to max chars.
        } else {
            if (s.length() > 3) {
                setValid(true);
            }
            if (s.length() == maxChars && maxChars > 0) {
                delegate.onZipCodeValid();
            } else {
                setValid(false);
            }
        }
    }

    public void formatAndSetText(String text) {
        watcherEnabled = false;
        this.setText(text);
        watcherEnabled = true;
    }

    public void setMaxChars(int maxChars) {
        if (maxChars <= 0) {
            return;
        }
        this.maxChars = maxChars;
    }
}
